/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.sevenheaven.segmentcontrol.utils;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.ComponentState;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.element.StateElement;
import timber.log.Timber;

/**
 * 颜色选择器工具类
 *
 * @since 2021-04-10
 */
public class ColorListHelper {
    private static final String TAG = ColorListHelper.class.getSimpleName();

    private ColorListHelper() {
        // do nothing
    }

    /**
     * 创建颜色选择器对象
     *
     * @param normalColor 未选择状态的颜色
     * @param selectedColor 选择状态的颜色
     * @return 选择器
     */
    public static StateElement makeWithNormalAndSelect(RgbColor normalColor, RgbColor selectedColor) {
        ShapeElement normalElement = new ShapeElement();
        normalElement.setRgbColor(normalColor);

        ShapeElement selectedElement = new ShapeElement();
        selectedElement.setRgbColor(selectedColor);

        StateElement background = new StateElement();
        background.addState(new int[]{ComponentState.COMPONENT_STATE_SELECTED}, selectedElement);
        background.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, normalElement);
        return background;
    }

    /**
     * 查询选择器
     *
     * @param stateElement 选择器
     * @param stateSet 状态集
     * @return 颜色
     */
    public static RgbColor getByState(StateElement stateElement, int[] stateSet) {
        // 查找相应状态 element 的 index
        int index = stateElement.findStateElementIndex(stateSet);
        if (index < 0) {
            Timber.e("stateSet=[%d] not found!", stateSet[0]);
            throw new IllegalArgumentException("stateSet not found!");
        }

        // 根据 index 取出 Element (这里是要取出颜色值，所以强转为 ShapeElement 再取)
        ShapeElement element = (ShapeElement) stateElement.getStateElement(index).getCurrentElement();
        return element.getRgbColors()[0];
    }
}
